MYBATIS动态查询语句
Introduction
mybatis的动态查询语句主要有一下几种:
- if
- choose
- where
- trim
- set
- foreach
1、if—最简单的动态sql
用来判断某个条件是否满足;当条件满足时,if包含的sql才会生效。1
2
3<if test="contentFile != null">
content_file_id = #{contentFile.id, javaType=int, jdbcType=INTEGER},
</if>
一般test中条件为判断是否为空,也可以判断是否等于某值,但是需要严格按照下面的格式1
2
3
4
5
6
7<if test="url == 'Y'.toString()">
url = #{url, javaType=string, jdbcType=CHAR},
</if>
<if test='url == "Y"'>
url = #{url, javaType=string, jdbcType=CHAR},
</if>
PS:注意以上单引号和双引号的位置。
还可以进行多条件判断1
2
3<if test="messageId != null and messageId != 0">
message_id = #{messageId, javaType=int, jdbcType=INTEGER}
</if>
2、choose
相当于switch,多数情况下和when以及otherwise联合使用,一下为借来的代码1
2
3
4
5
6
7
8
9
10
11
12
13
14<select id="dynamicChooseTest" parameterType="Blog" resultType="Blog">
select * from t_blog where 1 = 1
<choose>
<when test="title != null">
and title = #{title}
</when>
<when test="content != null">
and content = #{content}
</when>
<otherwise>
and owner = "owner1"
</otherwise>
</choose>
</select>
当when满足一个条件时,就会跳出choose,如果所有的when条件都未满足,则执行otherwise内的sql语句。
3、where
用于sql语句中的条件判断,优点是可以忽略where中的if所包含‘and’连接符。借来代码如下;1
2
3
4
5
6
7
8
9
10
11
12
13
14<select id="dynamicWhereTest" parameterType="Blog" resultType="Blog">
select * from t_blog
<where>
<if test="title != null">
title = #{title}
</if>
<if test="content != null">
and content = #{content}
</if>
<if test="owner != null">
and owner = #{owner}
</if>
</where>
</select>
当title为空,但是content不为空时,会将and content = #{content}
中的and忽略掉,同理语句中的or也可以忽略掉。
4、trim
可以再某些内容前面加上前缀,也可以在某些内容后面加上后缀,对应属性为prefix
和suffix
,当然,前后缀内容可以自己定义。
也可以将trim
包含的内容的特定内容忽略掉,前后缀都可,对应属性为prefixOverrides
和suffixOverrides
。
以下为利用trim来替代where语句,借来的代码。1
2
3
4
5
6
7
8
9
10
11
12
13
14<select id="dynamicTrimTest" parameterType="Blog" resultType="Blog">
select * from t_blog
<trim prefix="where" prefixOverrides="and |or">
<if test="title != null">
title = #{title}
</if>
<if test="content != null">
and content = #{content}
</if>
<if test="owner != null">
or owner = #{owner}
</if>
</trim>
</select>
5、set
用户update语句,主要功能时忽略以逗号结尾的set语句后面的逗号。另外,set内所有东西,不能全为空。1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20<set>
<if test="title != null">
title = #{title, javaType=string, jdbcType=CHAR},
</if>
<if test="description != null">
description = #{description, javaType=string, jdbcType=CHAR},
</if>
<if test="url != null">
url = #{url, javaType=string, jdbcType=CHAR},
</if>
<if test="contentFile != null">
content_file_id = #{contentFile.id, javaType=int, jdbcType=INTEGER},
</if>
<if test="order != null">
`order` = #{order, javaType=int, jdbcType=INTEGER},
</if>
<if test="messageId != null and messageId != 0">
message_id = #{messageId, javaType=int, jdbcType=INTEGER}
</if>
</set>
当messageId为
空,其他属性不为空时,就会忽略掉order
属性后面的逗号。
PS:这里的order
加了反引号,是因为order
在mysql
中被识别为关键字,所以加上反引号加以说明它是一个属性。反引号用“1”旁边的键输入。
6、foreach
主要用户查询条件中有“IN”的语句,具体还没用过,由于时间问题,先贴出参考链接,以后在整理。
http://haohaoxuexi.iteye.com/blog/1338557